package com.kdtech.analyse.Bbs.common;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
/**
 * ASP 论坛解析
 * @author KK
 */
public class BbsAspAnalyse implements AnalyseNews {


	
	public boolean isDetailPage(String url) {
		url = UrlArgumentTop.FromatUrl(url);
		url = StringUtils.substringAfterLast(url, "/");
		String[] regex = {
				"ShowPost.asp\\?ThreadID=[0-9]*"
				};
		return RegexUtils.matchAny(url, regex);
	}

	public NewsMeta parserHtml(UrlMeta urlMeta) {

		if (urlMeta.getHtml() == null) {
			return null;
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();

		String title = null;
		String content = null;
		Long date = null;
		Integer commnetNum = null;
		Integer clickNum = null;
		String updateUrl = url;
		String author=null;
		Document doc = Jsoup.parse(htmltxt);

		/*
		 * 标题
		 */
		title = doc.select("div.ForumPostTitle").text();
		/*
		 * 日期
		 */
		date = DateUtils.matchDate(doc.select("tr.CommonListTitle").text());
		
		/*
		 * 内容
		 */
		content = HtmlCleaner.getContentHtml(url, doc);
		
		/*
		 * 作者
		 */
		Elements authorList = doc.select(".ForumPostUserArea");
		if(authorList.size()>0)
		{
			author = authorList.get(0).text();
		}
		
		NewsMeta news = new NewsMeta();
		news.setUrl(url);
		news.setType(4);
		news.setTitle(StringUtils.trimSpace(title));
		news.setCommentNum(commnetNum);
		news.setClickNum(clickNum);
		news.setContent(StringUtils.trimSpace(content));
		news.setDate(date);
		news.setAuthor(author);
		news.setUpdateUrl(updateUrl);
		return news;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		String url = meta.getUpdateUrl();
		if (StringUtils.isNotBlank(url)){
			UrlMeta urlMeta = CrawlHTML.responseToURL(url);
			return parserHtml(urlMeta);
		}
		return null;
	}

	

	

}
